<?php
$basedir = dirname(__FILE__);

require_once $basedir . '/../classes/minime.php';

MiniMe::initialize();

if( count($argv) != 3) {
      echo "\n\tERROR!";
      echo "\n\t\tPlease provide USERNAME MESSAGE as parameters to this function.";
      echo "\n\n\tExample:";
      echo "\n\t\t" . 'php blog.php koski "Ready to Rock\'n\'Roll! "';
      echo "\n\n";
      exit;
}

$username = $argv[1];
$msg      = $argv[2];

$userLoader = new Minime_User_Loader(Minime::$conf);
$user = $userLoader->getUser($username);

if(!$user) {
    echo "\n\t\tDude, the username you want to add the blog post does not exists.";
    echo "\n\n";
    exit;
}

$atomLoader = new Minime_Atom_Loader(MiniMe::$conf);
$feed = $atomLoader->getFeed($username);

$array['id'] = Minime_HrefRenderer::getEntryLinkAlternate($username, time(), Minime::$conf);
$array['updated'] = date('c');
$array['alternate_href'] = $array['id'];
$array['title'] = $msg;
//$array['author']['uri'] = $feed->getAuthor()->getUri()->getUri();
$array['author']['uri'] = "acct:" . $user->getJid();
$array['author']['name'] = $user->getName();
$array['author']['link']['photo'] = $user->getLogo();
$array['author']['link']['alternate'] = Minime_HrefRenderer::getLdrrProfileHref($username, Minime::$conf);
$entry = Atom_Entry::buildFromArray($array);

// And let's create the activity verb
$as_verb = new Activitystream_Verb(Activitystream_Verb::VERB_POST);

$as_object = new Activitystream_Object();
$as_object->addChildElement(new Activitystream_ObjectType(Activitystream_ObjectType::TYPE_NOTE));
$as_object->addChildElement(new Atom_Entry_Id($array['id']));
$as_object->addChildElement(new Atom_Entry_Content($msg, Atom_Entry_Content::TYPE_HTML));
$as_object->addChildElement(new Atom_Entry_Link_AlternateHtml($array['id']));

$entry->addChildElement($as_verb);
$entry->addChildElement($as_object);

$feed->addChildElement($entry);
$feed->updateUpdated();

$atomStorer = new Minime_Atom_Storer(MiniMe::$conf);
$atomStorer->storeAtom($username, $feed);

//Pubsubhubbub Magic - A.K.A a TERRIBLE HACK!!!!
$copyOfFeed = $feed->createCopyWithoutEntries();
$copyOfFeed->addChildElement($entry);

$subscribersLoader = new Minime_Pubsubhubbub_Subscribers_Loader(Minime::$conf);
$subid = Pubsubhubbub_Subscribe::createID(Minime_HrefRenderer::getLdrrAtomHref($username, Minime::$conf));
echo "\n\n\tReady to Send Pubsub subscriptions of node " . Minime_HrefRenderer::getLdrrAtomHref($username, Minime::$conf) . " (" .$subid . ")";
$subscribers = $subscribersLoader->getSubscribers($subid);
echo "\n\tData to be send:";
echo "\n" . $copyOfFeed->asXML();

if($subscribers != null) {
    foreach ($subscribers->getSubscribers() as $subscriber) {
        // this is getting bigger and bigger hack!
        Pubsubhubbub_Publish::publish($subscriber->getCallback(), $subscriber->getSecret(), $copyOfFeed->asXML());   
    }
}

echo "\n\n\tDONE!\n";
